﻿using Com.Lancetinc.Evs.Helpers;
using Com.Lancetinc.Evs.Models;
using Com.Lancetinc.Evs.Services;
using NLog;
using System;
using System.Linq;
using System.Windows;
using System.Windows.Threading;
using Telerik.Windows.Controls;

namespace Com.Lancetinc.Evs.Controls
{
    /// <summary>
    /// VideoPreviewUserControl.xaml 的交互逻辑
    /// </summary>
    public partial class VideoPreviewUserControl
    {
        private static ILogger logger = LogManager.GetCurrentClassLogger();
        private bool mUnloaded = false;

        public VideoPreviewUserControl()
        {
            InitializeComponent();

            this.radWebCam.MinWidth = 150;
            this.radWebCam.MinHeight = 150;
            this.radWebCam.BorderThickness = new Thickness(0);
            this.radWebCam.Background = this.Background;
        }

        private void UserControl_Unloaded(object sender, RoutedEventArgs e)
        {
            mUnloaded = true;
            radWebCam.ShutDown();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            var instManager = ActiveApp.Instance.InstManager;

            var flipConfig = VideoStartRecordHelper.GetVideoFlipConfig();
            radWebCam.FlipHorizontally = flipConfig.FlipHorizontally;
            radWebCam.FlipVertically = flipConfig.FlipVertically;
            this.VideoRotationAngle = instManager.Instrument.GetVideoRotationAngle();
        }

        public void Play(VideoDeviceInfo videoDeviceInfo)
        {
            var dispatcherTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromMilliseconds(300)
            };
            dispatcherTimer.Tick += (_, _) =>
            {
                if (mUnloaded)
                {
                    return;
                }

                if (dispatcherTimer.Interval.TotalMilliseconds == 3000)
                {
                    dispatcherTimer.Stop();
                    try
                    {
                        var ok = RadWebCamHelper.LoadWhiteBalance(videoDeviceInfo.DeviceName);
                        logger.Debug("LoadWhiteBlance:" + ok);
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex);
                    }

                    return;
                }

                if (radWebCam.IsEnabled)
                {
                    dispatcherTimer.Stop();

                    var videoDevices = RadWebCam.GetVideoCaptureDevices();
                    var device = videoDevices.First(x => x.FriendlyName == videoDeviceInfo.DeviceName);
                    var videoFormat = RadWebCamHelper.GetVideoFormat(device, videoDeviceInfo);
                    radWebCam.Initialize(device, videoFormat, null);
                    radWebCam.Start();

                    dispatcherTimer.Interval = TimeSpan.FromSeconds(3);
                    dispatcherTimer.Start();
                }
            };
            dispatcherTimer.Start();
        }

        #region VideoRotationAngle

        public static readonly DependencyProperty VideoRotationAngleProperty =
            DependencyProperty.Register("VideoRotationAngle", typeof(double), typeof(VideoPreviewUserControl));

        public double VideoRotationAngle
        {
            get => (double)GetValue(VideoRotationAngleProperty);
            set => SetValue(VideoRotationAngleProperty, value);
        }

        #endregion
    }
}